<?php

namespace frontend\modules\comment\controllers;

use api\modules\v1\models\Wxuser;
use frontend\modules\base\controllers\BaseController;
use frontend\modules\comment\models\CommentImages;
use frontend\modules\goods\models\Goods;
use frontend\modules\orders\models\OrderGoods;
use frontend\modules\orders\models\OrderInfo;
use Yii;
use frontend\modules\comment\models\Comment;
use frontend\modules\comment\models\search\CommentSearch;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * 用户评论，评价级别，图片评论，评论内容查询等
 *
 * Class CommentController
 * @package frontend\modules\comment\controllers
 */
class CommentController extends BaseController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 添加评价
     * @desc
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $data[content] |评论内容|yes|
     * @param string $data[comment_rank] |商品ID|yes|40位|
     * @param string $data[is_niming] |是否匿名|yes|1：是，0：不是|
     * @param string $data[goods_id] |商品ID|yes|40位|
     *
     * @return string data[].userid 用户ID
     * @return string data[].unionid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionAddcomment()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $comment = new Comment();
        $comment->goods_id = $postData['goods_id'];
        $comment->attrcat_id = Goods::findOne($comment->goods_id)->attr_cat_id;
        $comment->add_time  = time();
        $comment->comment_rank = $postData['comment_rank'];
        $comment->content = $postData['content'];
        $comment->is_niming = $postData['is_niming'];
        $comment->user_id = $post['userid'];
        if(Yii::$app->session->get('user_name')) {
             $user_name = Yii::$app->session->get('user_name');
        }  else{
            $user_name = Wxuser::findOne($comment->user_id)->username;
        }
        $comment->user_name = $user_name;
        if($comment->save()){
            $message = ['code'=>200,'message'=>'添加评价成功'];
            return  json_encode($message);
        }
        $message = ['code'=>500,'message'=>'添加评价失败'];
        return json_encode($message);
    }

    /**
     * 多个商品添加评价
     * @desc data[ 0=>[  content=>ninninininin, comment_rank=>5, is_niming=>1, goods_id=>ASD4F56AS4DF654 ] ，1=>[ content=>ninninininin, comment_rank=>5, is_niming=>1 goods_id=>ASD4F56AS4DF654 ]
     * ]
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $data[0][content] |评论内容|yes|
     * @param string $data[0][comment_rank] |商品ID|yes|40位|
     * @param string $data[0][is_niming] |是否匿名|yes|1：是，0：不是|
     * @param string $data[0][goods_id] |商品ID|yes|40位|
     *
     * @param string $data[1][content] |评论内容|yes|
     * @param string $data[1][comment_rank] |商品ID|yes|40位|
     * @param string $data[1][is_niming] |是否匿名|yes|1：是，0：不是|
     * @param string $data[1][goods_id] |商品ID|yes|40位|
     *
     * @return string data[].userid 用户ID
     * @return string data[].unionid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionAddcomments()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
//        $postData =

        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $beginTransaction = Yii::$app->db->beginTransaction();
                try{
                    foreach($postData  as $key =>$val){
                        $comment = Comment::findOne(['order_goods_id'=>$val['rec_id']]);
                        if(!$comment) {
                            $comment = new Comment();
                            $comment->order_goods_id = $val['rec_id'];
                        }
                        $comment->goods_id = $val['goods_id'];
                        $comment->attrcat_id = Goods::findOne($comment->goods_id)->attr_cat_id;
                        $comment->add_time  = time();
                        $comment->comment_rank = $val['comment_rank'];
                        $comment->content = $val['content'];
                        $comment->is_niming = $val['is_niming'];
                        $comment->user_id = Yii::$app->UserInfo->userid;
                        $comment->is_show = 1;
                        if(Yii::$app->session->get('user_name')) {
                            $user_name = Yii::$app->session->get('user_name');
                        }  else{
                            $user_name = Wxuser::findOne($comment->user_id)->username;
                        }
                        $comment->user_name = $user_name;
                        if(!$comment->save()){
                            $beginTransaction->rollBack();
                            throw new Exception(json_encode($comment->errors));
                        }
                        $order_id = OrderGoods::findOne($comment->order_goods_id)->order_id;
                        $order = OrderInfo::findOne($order_id);
                        $order->order_status = 4;
                        $order->comment_status = 1;
                        if(!$order->save()){
                            $beginTransaction->rollBack();
                            throw new Exception(json_encode($order->errors));
                        }
                    }
                    $beginTransaction->commit();
                    $message = ['code'=>200,'message'=>'添加评价成功'];
                    return  json_encode($message);
                }catch (Exception $e){
                    $beginTransaction->rollBack();
                    $message = ['code'=>500,'message'=>'添加评价失败:'.$e->getMessage()];
                    return  json_encode($message);
                }
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 获取订单商品数据
     * @desc 评价页面根据订单获取需要评价的商品信息
     *
     * @param string $token_access |用户token|yes|32位|
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCommentorder()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $order_id = $postData['order_id'];
        $orderGoods = array();
        if($order_id) {
            $orderGoods = OrderGoods::find()->where(['order_id'=>$order_id])->asArray()->all();
        }
        $message = ['code'=>200,'message'=>'获取订单商品数据成功','data'=>$orderGoods];
        return json_encode($message);
    }




    /**
     * 图片上传
     * @return string
     */
    public function actionUpload()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $post = $_POST;
                $imgStr =isset($post['imgStr'])?$post['imgStr']:'';
                $imgStr = str_replace(" ","+",$imgStr);
                $order_goods_id = isset($post['recid'])?$post['recid']:'';

                $baseUrl = Yii::$app->basePath;
                $webUrlBaseOnApp= '/web/upload/comment/'.$order_goods_id.'/';
                $baseImages = $baseUrl.$webUrlBaseOnApp;
                is_dir($baseImages) OR mkdir($baseImages, 0777, true);

                $imageName = time().'-'.rand(10,1000).'.png';
                $finalPath = $baseImages.$imageName;

                if (!preg_match('/data:([^;]*);base64,(.*)/', $imgStr, $matches)) {
                    die("error");
                }

                $content = base64_decode($matches[2]);
                file_put_contents($finalPath,$content);

                $beginTransaction = Yii::$app->db->beginTransaction();
                try{
                    $comment = Comment::findOne(['order_goods_id'=>$order_goods_id]);
                    if($comment) {
                        $commentImages = new CommentImages();
                        $commentImages->comment_image = $webUrlBaseOnApp.$imageName;
                        $commentImages->comment_id = $comment->comment_id;
                        if(!$commentImages->save()){
                            throw new Exception(json_encode($commentImages->errors));
                        }
                    } else{
                        $comment = new Comment();
                        $orderGoods = OrderGoods::findOne($order_goods_id);
                        $comment->goods_id = $orderGoods->goods_id;
                        $comment->attrcat_id = $orderGoods->attr_cat_id;
                        $comment->add_time  = time();
                        $comment->comment_rank = 5;
                        $comment->content = '';
                        $comment->is_niming = 0;
                        $comment->user_id = $orderGoods->user_id;
                        $comment->order_goods_id = $order_goods_id;
                        if(!$comment->save()){
                            throw new Exception(json_encode($comment->errors));
                        }

                        $commentImages = new CommentImages();
                        $commentImages->comment_image = $webUrlBaseOnApp.$imageName;
                        $commentImages->comment_id = $comment->comment_id;
                        if(!$commentImages->save()){
                            throw new Exception(json_encode($commentImages->errors));
                        }
                    }
                    $beginTransaction->commit();
                    $message = ['code'=>200,'message'=>"图片上传成功",'data'=>$webUrlBaseOnApp.$imageName,'comment_images_id'=>$commentImages->comment_images_id];
                    return json_encode($message);
                } catch (Exception $e) {
                    $beginTransaction->rollBack();
                    $message = ['code'=>500,'message'=>$e->getMessage(),'data'=>[]];
                    return json_encode($message);
                }
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 图片删除
     */
    public function actionDelimage()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $postData  = $this->post['data'];
                $order_goods_id = $postData['order_goods_id'];
                $comment_id = Comment::findOne(['order_goods_id'=>$order_goods_id])->comment_id;

                $comment_images_id = $postData['comment_images_id'];
                $commentImages = CommentImages::findOne(['comment_images_id'=>$comment_images_id]);
                unlink(Yii::$app->basePath.$commentImages->comment_image);
                $commentImages->delete();
                $message = ['code'=>200,'message'=>"图片删除成功",'data'=>[]];
                return json_encode($message);
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * @return string
     */
    public function actionGetimage()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $post = Yii::$app->request->post();
                $postData = $post['data'];
                $ordersn = $postData['order_sn'];
                $orderARR = CommentImages::find()
                    ->select('ci.*,og.rec_id,c.comment_id')
                    ->from('comment_images AS ci')
                    ->leftJoin('comment AS c','c.comment_id = ci.comment_id')
                    ->leftJoin('order_goods AS og','og.rec_id = c.order_goods_id')
                    ->leftJoin('order_info AS oi','oi.order_id = og.order_id')
                    ->where(['order_sn'=>$ordersn,'og.is_gift'=>1])
                    ->asArray()
                    ->All();

                $grouped = $this->array_group_by($orderARR,'rec_id');
                $message = ['code'=>200,'message'=>"图片上传成功",'data'=>$grouped];
                return json_encode($message);
            }
        } else {
            return $userinfo;
        }


    }

    public function array_group_by($arr, $key)
    {
        $grouped = [];
        foreach ($arr as $value) {
            $grouped[$value[$key]][] = $value;
        }
        if (func_num_args() > 2) {
            $args = func_get_args();
            foreach ($grouped as $key => $value) {
                $parms = array_merge([$value], array_slice($args, 2, func_num_args()));
                $grouped[$key] = call_user_func_array('array_group_by', $parms);
            }
        }
        return $grouped;
    }

    /**
     * 获取最后一条评价信息
     * @desc 获取最后一条评价信息
     *
     * @param string data[goods_id] |商品goods_id|yes|40位|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCommentinfo()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $comment =
        $comment = Comment::find()
            ->select('c.*,g.goods_name,u.wx_name,wx_images')
            ->from('comment AS c')
            ->leftJoin('goods AS g','c.goods_id = g.goods_id')
            ->leftJoin('user AS u','u.id = c.user_id')
            ->where(['c.goods_id'=>$postData['goods_id'],'c.is_show'=>1])
            ->orderBy(['add_time'=>SORT_DESC])
            ->asArray()
            ->one();
        if($comment){
            $commentImagesARR = CommentImages::find()->where(['comment_id'=>$comment['comment_id']])->asArray()->all();
            $comment['commentImages'] = $commentImagesARR;
            $message = ['code'=>200,'message'=>"获取一条评论成功",'data'=>$comment];
            return json_encode($message);
        }
        $message = ['code'=>200,'message'=>"无评论",'data'=>[]];
        return json_encode($message);
    }

    /**
     * 统计商品评价
     * @desc 统计商品评价
     *
     * @param string data[goods_id] |商品goods_id|yes|40位|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionTolcomment()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $goods_id = $postData['goods_id'];
        $allCom = Comment::find()->where(['goods_id'=>$goods_id,'is_show'=>1])->count();
        $CommentArr = CommentImages::find()
            ->select('ci.comment_id')
            ->from('comment_images AS ci')
            ->leftJoin('comment AS c','c.comment_id = ci.comment_id')
            ->leftJoin('goods AS g','c.goods_id = g.goods_id')
            ->where(['c.goods_id'=>$goods_id,'c.is_show'=>1])
            ->asArray()
            ->distinct(true)
            ->count();

        $aa01 = Comment::find()->andWhere(['goods_id'=>$goods_id])->andWhere(["is_show"=>1])->andWhere(['<','comment_rank',2])->count();
        $aa23 = Comment::find()->andWhere(['goods_id'=>$goods_id])->andWhere(["is_show"=>1])->andWhere(['>','comment_rank',1])->andWhere(['<','comment_rank',4])->count();
        $aa45 = Comment::find()->andWhere(['goods_id'=>$goods_id])->andWhere(["is_show"=>1])->andWhere(['>','comment_rank',3])->count();
        $message = ['code'=>200,'message'=>"获取评价统计成功",'data'=>[
            'allCount'=>$allCom,
            'allImages'=>$CommentArr,
            'all01'=>$aa01,
            'all23'=>$aa23,
            'all45'=>$aa45,
        ]];
        return json_encode($message);
    }


    /**
     * 查看所有评论
     * @desc 查看所有评论
     *
     * @param string data[goods_id] |商品goods_id|yes|40位|
     * @param string data[page] |评论页|yes|整型int|
     * @param string data[num] |评论页容量|yes|整型int|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCommentlist()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $goods_id = $postData['goods_id'];
        $page = $postData['page'];
        $num = isset($postData['num'])?$postData['num']:5;
        $allCom = Comment::find()
            ->select('c.*,u.wx_name,u.wx_images')
            ->from('comment AS c')
            ->leftJoin('user AS u','u.id = c.user_id')
            ->where(['goods_id'=>$goods_id,'is_show'=>1])
            ->orderBy(['add_time'=>SORT_DESC])
            ->offset($page*$num,$page*$num+$num)
            ->limit($num)
            ->asArray()
            ->all();
        foreach($allCom as $k=>$v) {
            $allCom[$k]['children'] = CommentImages::find()->where(['comment_id'=>$v['comment_id']])->asArray()->all();
        }
        $message = ['code'=>200,'message'=>"获取商品所有评价",'data'=>$allCom];
        return json_encode($message);
    }

    /**
     * 获取该评论的评价图片
     * @desc 获取该评论的评价图片
     *
     * @param string data[order_id] |商品goods_id|yes|40位|
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionZoomcomment()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $order_id = $postData['order_id'];
        $imagesAR = CommentImages::find()
            ->select('ci.*,og.rec_id,c.comment_id')
            ->from('comment_images AS ci')
            ->leftJoin('comment AS c','c.comment_id = ci.comment_id')
            ->leftJoin('order_goods AS og','og.rec_id = c.order_goods_id')
            ->leftJoin('order_info AS oi','oi.order_id = og.order_id')
            ->where(['oi.order_id'=>$order_id])
            ->asArray()
            ->All();

        $reAR = array();
        foreach($imagesAR as $k=>$v) {
            $reAR[$v['rec_id']][]=$v;
        }
        $message = ['code'=>200,'message'=>"获取评价图片成功",'data'=>$reAR];
        return json_encode($message);
    }
}
